/**
 *
 * @description:
 * @author: junyong.hong
 * @createTime: 2019/3/11
 * @version: 1.0.0.0
 * @history:
 *    1、
 *    2、
 *
 */
const mongoose = require('mongoose')
const Category = mongoose.model('Category')
const Movie = mongoose.model('Movie')
const rp = require('request-promise')
const _ = require('lodash')

// 对电影补充字段、信息
const updateMovies = async (movie) => {
    const options = {
        uri: `https://api.douban.com/v2/movie/subject/${movie.doubanId}`,
        json: true
    }

    const data = await rp(options)

    _.extend(movie, {
        country: data.countries[0],
        language: data.language,
        summary: data.summary
    })

    const genres = movie.genres

    if (genres && genres.length) {
        await Promise.all(genres.map(async genre => {
            let cat = await Category.findOne({
                name: genre
            })

            if (cat) {
                cat.movies.push(movie._id)

                await cat.save()
            } else {
                cat = new Category({
                    name: genre,
                    movies: [movie._id]
                })

                cat = await cat.save()

                movie.category = cat._id

                await movie.save()
            }
        }))
    } else {
        movie.save()
    }
}


// 到豆瓣查询相关的电影
exports.searchByDouban = async (q) => {
    const options = {
        uri: `https://api.douban.com/v2/movie/search?q=${encodeURIComponent(q)}`,
        json: true
    }

    const data = await rp(options)
    let subjects = []
    let movies = []

    if (data && data.subjects) {
        subjects = data.subjects
    }

    if (subjects.length) {
        let queryArray = []

        await Promise.all(subjects.map(async item => {
            let movie = await Movie.findOne({
                doubanId: item.id
            })

            if (movie) {
                movies.push(movie)
            } else {
                const directors = item.directors || []
                const director = directors[0] || {}

                movie = new Movie({
                    title: item.title,
                    director: director.name,
                    doubanId: item.id,
                    year: item.year,
                    genres: item.genres || [],
                    poster: item.images.large
                })

                movie = await movie.save()

                movies.push(movie)
            }
        }))

        movies.forEach(movie => {
            updateMovies(movie)
        })
    }

    return movies
}


// 根据分类名，查新分类
exports.findMoviesByCat = async (cat) => {
    const data = await Category.findOne({
        name: cat
    }).populate({
        path: 'movies',
        select: '_id title poster summary'
    })

    return data
}

// 搜索最热门、最冷门
exports.findHotMovies = async (hot, count) => {
    const data = await Movie.find({}).sort({ pv: hot }).limit(count)

    return data
}

// 根据分类搜索
exports.searchByCategroy = async (catId) => {
    const data = await Category.find({
        _id: catId
    }).populate({
        path: 'movies',
        select: '_id title poster',
        options: { limit: 8 }
    })

    return data
}

// 根据关键字搜索
exports.searchByKeyword = async (q) => {
    const data = await Movie.find({
        // i不区分大小写
        title: new RegExp(q + '.*', 'i')
    })

    return data
}

// 根据电影id搜索
exports.findMovieById = async (id) => {
    const data = await Movie.findOne({
        _id: id
    })

    return data
}

// 查找电影和分类
exports.fondMoviesAndCategory = async (fields) => {
    const data = await Movie.find({}).populate('category', fields)

    return data
}

// 根据分类id搜索
exports.findCategoryById = async (id) => {
    const data = await Category.findOne({
        _id: id
    })

    return data
}

// 查找所有的分类
exports.findCategories = async () => {
    const data = await Category.find({})

    return data
}
